package com.longy.gulimall.product.exception;

import com.longy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestControllerAdvice(basePackages = "com.longy.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {

        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        //1.获取错误结果的信息
        bindingResult.getFieldErrors().forEach((item) -> {
            //属性名
            String field = item.getField();
            //错误信息
            String defaultMessage = item.getDefaultMessage();
            map.put(field, defaultMessage);

        });
        return R.error(400,"数据检验出现问题").put("data",map);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e){
        log.info("服务器错误信息{}，错误类型{}",e.getMessage(),e.getClass());
        return R.error(500,"服务器内部错误，小哥哥正在修复");
    }
}

